#ifndef _MYTHREAD
#define _MYTHREAD

#include <iostream>
#include <pthread.h>
#include <string>
#include <functional>
#include "Log.hpp"
using namespace log_ns;
using namespace std;

namespace ThreadMoudle
{
    using func_t = function<void(const string &)>;

    class Thread
    {
    public:
        void Excute() // 线程执行任务
        {
            cout << _name << " is running" << endl;
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }

    public:
        Thread(const string &name, func_t func)
            : _name(name), _func(func)
        {
            cout << "create " << _name << " done" << endl;
        }
        static void *ThreadRoutine(void *arg)
        { // 新线程都会先执行这个函数
            Thread *self = static_cast<Thread *>(arg);
            self->Excute();
            return nullptr;
        }

        bool Start() // 线程开始启动
        {
            int res = pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (res != 0)
            {
                LOG(ERROR, "%s create fault", _name.c_str());
                return false;
            }
            LOG(DEBUG, "%s create successful", _name.c_str());
            return true;
        }

        void Stop()
        {
            if (_isrunning)
            {
                pthread_cancel(_tid);
                _isrunning = false;
                LOG(DEBUG, "%s is stop", _name.c_str());
                cout << _name << " Stop" << endl;
            }
        }

        void Join()
        {
            pthread_join(_tid, nullptr);
            cout << _name << " is Joined" << endl;
        }

        string Getname()
        {
            return _name;
        }
        ~Thread()
        {
            Stop();
        }

    private:
        string _name;    // 线程名
        pthread_t _tid;  // 线程ID
        bool _isrunning; // 是否在执行任务
        func_t _func;    // 要执行的回调函数
    };
};

#endif